package cn.User.service.impl;

import cn.User.dao.UserDao;
import cn.User.service.UserService;
import cn.util.aliyun.AliyunOSSClientUtil;
import cn.util.tool.Tool;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao  userDao;

    @Autowired
    Tool tool;


    @Override
    public int setUserHistory(Map<String, Object> params) {
        String url=params.get("LLURL").toString();
        params.put("SPBH",url.substring(url.length()-15,url.length()-5));
        return userDao.setUserHistory(params);
    }

    /**
     * 用户登陆
     * @param params
     * @return
     * type 1.账号密码登陆 2.手机号登陆 3.QQ登陆 4.微信登陆
     */
    public Map<String, Object> SuccessLogin(Map<String, Object> params, HttpServletRequest request) {

        Map<String, Object> result=new HashMap<>();
        int type=Integer.parseInt( params.get("type").toString());
        if(type==1){
            //普通账号密码登陆
            result.put("state",1);
            result.put("resultype","json");
        }else if(type==2){

        }else if(type==3){
            try {
                AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);

                String accessToken   = null,
                        openID        = null;
                long tokenExpireIn = 0L;

                if (accessTokenObj.getAccessToken().equals("")) {
//                我们的网站被CSRF攻击了或者用户取消了授权
//                做一些数据统计工作
                    System.out.print("没有获取到响应参数");
                } else {
                    //秘钥
                    accessToken = accessTokenObj.getAccessToken();
                    //报废时间
                    tokenExpireIn = accessTokenObj.getExpireIn();

                    // 利用获取到的accessToken 去获取当前用的openid -------- start
                    OpenID openIDObj =  new OpenID(accessToken);
                    //唯一的
                    openID = openIDObj.getUserOpenID();

                    //System.out.println("<p> start -----------------------------------利用获取到的accessToken,openid 去获取用户在Qzone的昵称等信息 ---------------------------- start </p>");
                    //与自己的类重名了！！！
                    UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                    UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                    //System.out.println("欢迎你:"+userInfoBean.getNickname());

                    System.out.println("QQ登陆IP:"+request.getRemoteAddr());
                    result.put("path","登陆成功");
                }
            } catch (QQConnectException e) {
                result.put("state",0);
                result.put("message",e.getMessage());
            }
        }else if(type==4){

        }
        //登陆成功，更新用户状态
         if(Integer.parseInt( result.get("state").toString())==1){
             UsernamePasswordToken token=new UsernamePasswordToken(params.get("ystUsername").toString(), params.get("ystPassword").toString());
             //当前用户线程
             Subject subject=SecurityUtils.getSubject();
             try {
                 subject.login(token);
                 Session session = subject.getSession();
                 System.out.println("sessionId:" + session.getId());
                 System.out.println("sessionHost:" + session.getHost());
                 System.out.println("sessionTimeout:" + session.getTimeout());
                 userDao.updateUserInfoState(params);
                 String loginName = (String) subject.getPrincipal();
                 System.out.println(loginName);
             } catch (UnknownAccountException ex) {
                 result.put("state",0);
                 result.put("message","用户不存在！");
             } catch (IncorrectCredentialsException ex) {
                 result.put("state",0);
                 result.put("message","密码错误！");
             }catch (ExcessiveAttemptsException ex) {
                 result.put("state",0);
                 result.put("message","账号或密码错误次数过多,请稍后重试！");
             } catch (AuthenticationException ex) {
                 result.put("state",0);
                 result.put("message",ex.getMessage());// 自定义报错信息
             } catch (Exception ex) {
                 ex.printStackTrace();
                 result.put("state","0");
                 result.put("message","内部错误，请重试！");
             }
         }
        return result;
    }

    /**
     * 获取用户信息
     * @param params
     * @return
     */
    public Map<String, Object> getuserinfo(Map<String, Object> params) {
        //当前用户线程
        Subject subject=SecurityUtils.getSubject();
        Map<String, Object> result=new HashMap<>();
        //登录成功
        if(subject.getPrincipal()!=null){
            params.put("YHBH",subject.getPrincipal());
            //用户基本信息
            result=userDao.getuserinfo(params);
            if (result!=null){
                //订单信息。。。。
            }
        }

        return result;
    }

    /**
     * 退出登陆
     * @param params
     * @return
     */
    public Map<String, Object> logout(Map<String, Object> params) {
        Map<String,Object> result=new HashMap<>();
        result.put("state",0);
        //当前用户线程
        Subject subject=SecurityUtils.getSubject();
        try {
            if(subject.getPrincipal()!=null) {
                params.put("YHBH", subject.getPrincipal());
                int state = userDao.logout(params);
                result.put("state", state);
                //Shrio退出
                subject.logout();
            }
        }catch (Exception e){
            e.getMessage();
        }

        return result;
    }

    @Override
    public Map<String, Object> islogin(Map<String, Object> params) {
        Map<String,Object> result=new HashMap<>();
        //当前用户线程
        Subject subject=SecurityUtils.getSubject();
        result.put("YHBH", subject.getPrincipal());
        return result;
    }


}
